import { getResponseMessage } from "@mallfoundry/client/message"
import { PhonePasswordCredentials, SubjectHolder } from "@mallfoundry/keystone/security"
import { Alert, Button, Card, Checkbox, Col, Divider, Form, Input, Row } from "antd"
import *  as CryptoJS from "crypto-js"
import * as React from "react"
import { useState } from "react"
import { Link, useHistory } from "react-router-dom"
import classes from "./index.module.scss"

export default function Login() {
  const history = useHistory()
  const [signing, setSigning] = useState(false)
  const [signError, setSignError] = useState("")

  function handleSignIn(values: any) {
    const credentials = new PhonePasswordCredentials()
    credentials.countryCode = "86"
    credentials.phone = values.phone
    credentials.password = CryptoJS.MD5(values.password).toString()
    setSignError("")
    setSigning(true)
    SubjectHolder.login(credentials)
      .then(() => history.push("/stores"))
      .catch(reason => setSignError(getResponseMessage(reason)))
      .finally(() => setSigning(false))
  }

  return (
    <div className={classes.Login}>
      <Row>
        <Col offset={8} span={7}>
          <Card bordered={false} title={<h3>密码登录</h3>}>
            {signError && <Form.Item>
              <Alert type="error" message={signError} closable afterClose={() => setSignError("")}/>
            </Form.Item>}
            <Form name="loginForm" initialValues={{ remember: true }} size="large" onFinish={handleSignIn}>
              <Form.Item name="phone" rules={[{ required: true, message: "请输入手机号" }]}>
                <Input placeholder="请输入手机号"/>
              </Form.Item>
              <Form.Item name="password" rules={[{ required: true, message: "请输入密码" }]}>
                <Input.Password placeholder="请输入密码"/>
              </Form.Item>
              <Form.Item name="remember" valuePropName="checked">
                <Checkbox>三天内自动登录</Checkbox>
              </Form.Item>
              <Form.Item>
                <Button block type="primary" htmlType="submit" loading={signing}>
                  {signing ? "登录中..." : "登录"}
                </Button>
              </Form.Item>
              <Form.Item noStyle>
                <Row justify="end">
                  <Col className={classes.BottomActions}>
                    <Link to="/retake">忘记密码</Link>
                    <Divider type="vertical"/>
                    <Link to="/signup">免费注册</Link>
                  </Col>
                </Row>
              </Form.Item>
            </Form>
          </Card>
        </Col>
      </Row>
    </div>

  )
}
